<?php
include('lib.php');

$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';

switch (strtolower($mode)) {
	case 'search':
		$keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';

		$url = "http://chacha.vn/search/result?search_type=song&search_text=" . urlencode(utf8_encode($keyword)) . "&show_type=&page=1";

		$input = @file_get_contents($url) or die("Could not access file: $url");
		$songInfo = array();

		$regexp1 = "<a href=\"#\" class=\"song\" onclick=\"playlist\[0\].playOnClick\((\d*)\); return false;\">(.*)<\/a>(\s*)<div class=\"artist\">(.*)<\/div>"; // Get song title
		$regexp2 = "<script>playlist\[0\]\.songId\[(\d*)\]=(\d*)<\/script>";
		$regexp3 = "<script>playlist\[0\]\.songDuration\[(\d*)\]=\"(\d*)\"<\/script>";

		if(preg_match_all("/$regexp1/siU", $input, $matches, PREG_SET_ORDER))
		{
			foreach($matches as $match)
			{
				$songInfo[$match[1]]['title'] = trim($match[2]);
				$songInfo[$match[1]]['artist'] = trim(strip_tags($match[4]));
			}
		}

		if(preg_match_all("/$regexp2/siU", $input, $matches, PREG_SET_ORDER))
		{
			foreach($matches as $match)
			{
				$songInfo[$match[1]]['id'] = trim($match[2]);
			}
		}

		if(preg_match_all("/$regexp3/siU", $input, $matches, PREG_SET_ORDER))
		{
			foreach($matches as $match)
			{
				$songInfo[$match[1]]['duration'] = trim($match[2]);
			}
		}
		echo $_GET['jsoncallback'] . '(' . array2json($songInfo) . ');';

		break;
	case 'playlist':
		$ouput = "<asx version='3.0'>\n";
		$output .= "<title>Playlist @ Music Hunter</title>\n";
		$cookie = isset($_COOKIE['playlist_hunter']) ? $_COOKIE['playlist_hunter'] : '';
		if ($cookie <> ""){
			$arr = explode("|", $cookie);
			for ($i = 0; $i < count($arr); $i++){
				$songInfo = split("@", $arr[$i]);
				$output .= "<entry>\n";
				$output .= "	<title>". $songInfo[1] ."</title>\n";
				$output .= "	<ref href='" . $songInfo[0] . "' />\n";
				$output .= "</entry>\n";
			}
		}
		$output .= "</asx>";
		print $output;
		break;
	case 'getsong':
		$songId = isset($_GET['id']) ? $_GET['id'] : '';
		$url = "http://chacha.vn/song/getUrl?id=$songId&songTable=1";
		$input = @file_get_contents($url) or die("Could not access file: $url");
		print $input;
		break;
}
?>
